package evaluatetask

import (
	"ZHONGYIHANGYAN/bean/dbModel"
	"ZHONGYIHANGYAN/bean/request"
	"ZHONGYIHANGYAN/bean/response"
	commUtils "ZHONGYIHANGYAN/commUtils"
	"fmt"
	"time"
)

// 辅助函数：安全地格式化时间指针
func formatTimePtr(t *time.Time) string {
	if t == nil {
		return ""
	}
	return t.Format("2006-01-02 15:04:05")
}

// 获取评价任务列表
func (manage *EvaluateTaskManage) GetEvaluateTaskList(query *request.GetEvaluateTaskListQuery) (response.PageData, error) {
	pageData := response.PageData{}

	db := manage.DataBase.DB()
	tx := db.Model(&dbModel.EvaluateTask{})

	// 根据任务名称模糊查询
	if query.Name != "" {
		tx = tx.Where("name LIKE ?", "%"+query.Name+"%")
	}

	// 获取总记录数
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return pageData, err
	}
	if total == 0 {
		pageData.List = []interface{}{}
		return pageData, nil
	}

	// 分页查询
	currentPage := query.CurrentPage
	numPerPage := query.NumPerPage
	if currentPage <= 0 {
		currentPage = 1
	}
	if numPerPage <= 0 {
		numPerPage = 50
	}
	offset := (currentPage - 1) * numPerPage
	tx = tx.Order("create_time DESC").Limit(numPerPage).Offset(offset)

	var taskList []dbModel.EvaluateTask
	if err := tx.Find(&taskList).Error; err != nil {
		return pageData, err
	}

	var taskIds []string
	for _, task := range taskList {
		taskIds = append(taskIds, task.Id)
	}

	// 批量获取专家与评价任务关系记录
	var expertAndEvaluateTaskRelationshipList []dbModel.ExpertAndEvaluateTaskRelationship
	if len(taskIds) > 0 {
		db.Where("task_id IN ?", taskIds).Find(&expertAndEvaluateTaskRelationshipList)
	}

	// 构建任务ID到专家ID的映射
	expertIdMap := make(map[string][]string)
	for _, relationship := range expertAndEvaluateTaskRelationshipList {
		expertIdMap[relationship.TaskId] = append(expertIdMap[relationship.TaskId], relationship.ExpertId)
	}

	// 转换为响应格式
	var responseList []response.GetEvaluateTaskListResponse
	for _, task := range taskList {
		// 从映射中获取专家ID列表
		expertIds := expertIdMap[task.Id]
		if expertIds == nil {
			expertIds = []string{}
		}
		fmt.Println("task.ResourceType", task)

		responseItem := response.GetEvaluateTaskListResponse{
			Id:            task.Id,
			Name:          task.Name,
			Desc:          task.Desc,
			ResourceType:  task.ResourceType,
			ResourceId:    task.ResourceId,
			ResourceName:  task.ResourceName,
			TemplateId:    task.TemplateId,
			TemplateName:  task.TemplateName,
			PlanDuration:  task.PlanDuration,
			RealDuration:  task.RealDuration,
			StartTime:     formatTimePtr(task.StartTime),
			EndTime:       formatTimePtr(task.EndTime),
			LastStartTime: formatTimePtr(task.LastStartTime),
			ExecStatus:    task.ExecStatus,
			SegmentTime:   task.SegmentTime,
			ExpertIds:     expertIds,
			CreateTime:    task.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:    task.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		responseList = append(responseList, responseItem)
	}

	pageData.CurrentPage = currentPage
	pageData.NumPerPage = numPerPage
	pageData.TotalCount = int(total)
	pageData.TotalPages = (pageData.TotalCount + numPerPage - 1) / numPerPage
	pageData.List = responseList

	return pageData, nil
}

// 添加或修改评价任务
func (manage *EvaluateTaskManage) AddOrUpdateEvaluateTask(task *request.AddOrUpdateEvaluateTaskQuery) (string, error) {
	fmt.Printf("===== 开始添加或修改评价任务 =====\n")
	fmt.Printf("操作类型: %s\n", map[bool]string{true: "修改", false: "新增"}[task.Id != ""])
	fmt.Printf("任务ID: %s\n", task.Id)
	fmt.Printf("任务名称: %s\n", task.Name)
	fmt.Printf("执行状态: %d\n", task.ExecStatus)
	fmt.Printf("专家数量: %d\n", len(task.ExpertIds))

	db := manage.DataBase.DB()

	// 开启事务确保数据一致性
	tx := db.Begin()
	if tx.Error != nil {
		return "", fmt.Errorf("开启事务失败: %v", tx.Error)
	}
	fmt.Println("事务已开启")

	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			fmt.Printf("发生panic，事务已回滚: %v\n", r)
		}
	}()

	isUpdate := task.Id != ""

	var taskId string
	currentTime := time.Now().Local() // 确保使用本地时区

	if !isUpdate {
		// 新增评价任务
		taskId = commUtils.GenUUID()
		fmt.Printf("生成新任务ID: %s\n", taskId)

		taskToCreate := dbModel.EvaluateTask{
			Id:           taskId,
			Name:         task.Name,
			Desc:         task.Desc,
			ResourceType: task.ResourceType,
			ResourceId:   task.ResourceId,
			ResourceName: task.ResourceName,
			TemplateId:   task.TemplateId,
			TemplateName: task.TemplateName,
			PlanDuration: task.PlanDuration,
			SegmentTime:  task.SegmentTime,
			ExecStatus:   task.ExecStatus, // 默认状态：0-未开始
		}

		// 如果状态为1（开始评价），设置开始时间
		if task.ExecStatus == 1 {
			taskToCreate.StartTime = &currentTime
			taskToCreate.LastStartTime = &currentTime
			fmt.Printf("设置开始时间: %s (Unix: %d, 时区: %s)\n",
				currentTime.Format("2006-01-02 15:04:05"),
				currentTime.Unix(),
				currentTime.Location())
		}

		fmt.Println("开始创建评价任务...")
		if err := tx.Create(&taskToCreate).Error; err != nil {
			tx.Rollback()
			fmt.Printf("创建评价任务失败: %v\n", err)
			return "", fmt.Errorf("创建评价任务失败: %v", err)
		}
		fmt.Println("评价任务创建成功")
	} else {
		// 修改评价任务
		taskId = task.Id
		fmt.Printf("修改现有任务，任务ID: %s\n", taskId)

		// 如果修改后的状态为1，需要先查询当前任务信息来处理时间字段
		var currentTask dbModel.EvaluateTask
		if task.ExecStatus == 1 {
			fmt.Println("查询当前任务信息（用于时间字段处理）...")
			if err := tx.Where("id = ?", taskId).First(&currentTask).Error; err != nil {
				tx.Rollback()
				if err.Error() == "record not found" {
					fmt.Printf("任务不存在: %s\n", taskId)
					return "", fmt.Errorf("评价任务不存在")
				}
				fmt.Printf("查询任务失败: %v\n", err)
				return "", fmt.Errorf("查询评价任务失败: %v", err)
			}
			fmt.Println("当前任务信息查询成功")
		}

		updateData := map[string]interface{}{
			"name":          task.Name,
			"desc":          task.Desc,
			"resource_type": task.ResourceType,
			"resource_id":   task.ResourceId,
			"resource_name": task.ResourceName,
			"template_id":   task.TemplateId,
			"template_name": task.TemplateName,
			"plan_duration": task.PlanDuration,
			"segment_time":  task.SegmentTime,
			"exec_status":   task.ExecStatus,
		}

		// 如果状态为1（开始评价），设置时间字段
		if task.ExecStatus == 1 {
			// StartTime如果已经有值就不更新，没有值就设置为当前时间
			if currentTask.StartTime == nil {
				updateData["start_time"] = &currentTime
				fmt.Printf("设置StartTime: %s (Unix: %d, 时区: %s)\n",
					currentTime.Format("2006-01-02 15:04:05"),
					currentTime.Unix(),
					currentTime.Location())
			} else {
				fmt.Printf("StartTime已存在，不更新: %s (Unix: %d, 时区: %s)\n",
					currentTask.StartTime.Format("2006-01-02 15:04:05"),
					currentTask.StartTime.Unix(),
					currentTask.StartTime.Location())
			}
			// LastStartTime每次都更新
			updateData["last_start_time"] = &currentTime
			fmt.Printf("更新LastStartTime: %s (Unix: %d, 时区: %s)\n",
				currentTime.Format("2006-01-02 15:04:05"),
				currentTime.Unix(),
				currentTime.Location())
		}

		fmt.Println("开始更新评价任务...")
		result := tx.Model(&dbModel.EvaluateTask{}).Where("id = ?", taskId).Updates(updateData)
		if result.Error != nil {
			tx.Rollback()
			fmt.Printf("更新评价任务失败: %v\n", result.Error)
			return "", fmt.Errorf("更新评价任务失败: %v", result.Error)
		}
		if result.RowsAffected == 0 {
			tx.Rollback()
			fmt.Printf("更新失败，未找到记录: %s\n", taskId)
			return "", fmt.Errorf("更新评价任务失败：ID 为 %s 的记录未找到", taskId)
		}
		fmt.Printf("评价任务更新成功，受影响行数: %d\n", result.RowsAffected)
	}

	// 处理专家与评价任务关系记录
	fmt.Println("开始处理专家关系记录...")
	if isUpdate {
		// 修改任务时，先删除原有的专家关系记录
		fmt.Println("删除原有专家关系记录...")
		if err := tx.Where("task_id = ?", taskId).Delete(&dbModel.ExpertAndEvaluateTaskRelationship{}).Error; err != nil {
			tx.Rollback()
			fmt.Printf("删除原有专家关系记录失败: %v\n", err)
			return "", fmt.Errorf("删除原有专家关系记录失败: %v", err)
		}
		fmt.Println("原有专家关系记录删除成功")
	}

	// 创建新的专家与评价任务关系记录
	if len(task.ExpertIds) > 0 {
		fmt.Printf("创建新的专家关系记录，专家数量: %d\n", len(task.ExpertIds))
		var expertList []dbModel.ExpertAndEvaluateTaskRelationship
		for _, expertId := range task.ExpertIds {
			expert := dbModel.ExpertAndEvaluateTaskRelationship{
				Id:       commUtils.GenUUID(),
				TaskId:   taskId,
				ExpertId: expertId,
			}
			expertList = append(expertList, expert)
		}
		if err := tx.CreateInBatches(expertList, 100).Error; err != nil {
			tx.Rollback()
			fmt.Printf("创建专家与评价任务关系记录失败: %v\n", err)
			return "", fmt.Errorf("创建专家与评价任务关系记录失败: %v", err)
		}
		fmt.Println("专家关系记录创建成功")
	} else {
		fmt.Println("无专家关系记录需要创建")
	}

	// 提交事务
	fmt.Println("开始提交事务...")
	if err := tx.Commit().Error; err != nil {
		fmt.Printf("提交事务失败: %v\n", err)
		return "", fmt.Errorf("提交事务失败: %v", err)
	}

	fmt.Printf("===== 操作完成 =====\n")
	fmt.Printf("任务ID: %s\n", taskId)
	fmt.Printf("事务已成功提交\n\n")

	return taskId, nil
}

// 删除评价任务
func (manage *EvaluateTaskManage) DeleteEvaluateTask(evaluateTaskIds []string) error {
	if len(evaluateTaskIds) == 0 {
		return nil
	}

	db := manage.DataBase.DB()

	// 开启事务确保数据一致性
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 删除评价任务记录
	result := tx.Where("id IN ?", evaluateTaskIds).Delete(&dbModel.EvaluateTask{})
	if result.Error != nil {
		tx.Rollback()
		return fmt.Errorf("删除评价任务失败: %v", result.Error)
	}
	if result.RowsAffected == 0 {
		tx.Rollback()
		return fmt.Errorf("没有找到要删除的评价任务记录，ID列表可能无效或记录已被删除")
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return fmt.Errorf("提交事务失败: %v", err)
	}

	return nil
}

// 获取评价任务详情
func (manage *EvaluateTaskManage) GetEvaluateTaskDetail(query *request.GetEvaluateTaskDetailQuery) (*response.GetEvaluateTaskDetailResponse, error) {
	db := manage.DataBase.DB()

	// 查询评价任务基本信息
	var task dbModel.EvaluateTask
	if err := db.Where("id = ?", query.EvaluateTaskId).First(&task).Error; err != nil {
		if err.Error() == "record not found" {
			return nil, fmt.Errorf("评价任务不存在")
		}
		return nil, fmt.Errorf("查询评价任务失败: %v", err)
	}

	// 构建响应数据
	response := &response.GetEvaluateTaskDetailResponse{
		Id:            task.Id,
		Name:          task.Name,
		Desc:          task.Desc,
		ResourceId:    task.ResourceId,
		ResourceName:  task.ResourceName,
		TemplateId:    task.TemplateId,
		TemplateName:  task.TemplateName,
		PlanDuration:  task.PlanDuration,
		RealDuration:  task.RealDuration,
		StartTime:     formatTimePtr(task.StartTime),
		EndTime:       formatTimePtr(task.EndTime),
		LastStartTime: formatTimePtr(task.LastStartTime),
		ExecStatus:    task.ExecStatus,
		SegmentTime:   task.SegmentTime,
		CreateTime:    task.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:    task.UpdateTime.Format("2006-01-02 15:04:05"),
	}

	return response, nil
}

// 更新评价任务状态
func (manage *EvaluateTaskManage) UpdateEvaluateTaskStatus(query *request.UpdateEvaluateTaskStatusQuery) error {
	if query.EvaluateTaskId == "" {
		return fmt.Errorf("评价任务ID不能为空")
	}

	if query.Time == "" {
		return fmt.Errorf("时间参数不能为空")
	}

	// 解析传入的时间，使用本地时区
	location, _ := time.LoadLocation("Local")
	currentTime, err := time.ParseInLocation("2006-01-02 15:04:05", query.Time, location)
	if err != nil {
		return fmt.Errorf("时间格式错误: %v", err)
	}

	fmt.Printf("===== 更新评价任务状态 =====\n")
	fmt.Printf("任务ID: %s\n", query.EvaluateTaskId)
	fmt.Printf("目标状态: %d\n", query.ExecStatus)
	fmt.Printf("传入时间: %s\n", query.Time)
	fmt.Printf("解析后时间: %s\n", currentTime.Format("2006-01-02 15:04:05"))
	fmt.Printf("解析后时间(Unix): %d\n", currentTime.Unix())
	fmt.Printf("解析后时间(时区): %s\n", currentTime.Location())

	db := manage.DataBase.DB()

	// 首先查询当前任务的状态和时间信息
	var currentTask dbModel.EvaluateTask
	if err := db.Where("id = ?", query.EvaluateTaskId).First(&currentTask).Error; err != nil {
		if err.Error() == "record not found" {
			return fmt.Errorf("评价任务不存在")
		}
		return fmt.Errorf("查询评价任务失败: %v", err)
	}

	fmt.Printf("当前任务状态: %d\n", currentTask.ExecStatus)
	fmt.Printf("当前RealDuration: %d秒\n", currentTask.RealDuration)
	if currentTask.StartTime != nil {
		fmt.Printf("StartTime: %s (Unix: %d, 时区: %s)\n",
			currentTask.StartTime.Format("2006-01-02 15:04:05"),
			currentTask.StartTime.Unix(),
			currentTask.StartTime.Location())
	} else {
		fmt.Println("StartTime: 未设置")
	}
	if currentTask.LastStartTime != nil {
		fmt.Printf("LastStartTime: %s (Unix: %d, 时区: %s)\n",
			currentTask.LastStartTime.Format("2006-01-02 15:04:05"),
			currentTask.LastStartTime.Unix(),
			currentTask.LastStartTime.Location())
	} else {
		fmt.Println("LastStartTime: 未设置")
	}
	if currentTask.EndTime != nil {
		fmt.Printf("EndTime: %s (Unix: %d, 时区: %s)\n",
			currentTask.EndTime.Format("2006-01-02 15:04:05"),
			currentTask.EndTime.Unix(),
			currentTask.EndTime.Location())
	} else {
		fmt.Println("EndTime: 未设置")
	}

	// 准备更新的数据
	updateData := map[string]interface{}{
		"exec_status": query.ExecStatus,
	}

	// 根据不同的状态执行相应的逻辑
	switch query.ExecStatus {
	case 1: // 开始评价
		fmt.Printf("=== 开始评价时间设置 ===\n")
		// StartTime如果已经有值就不更新，没有值就设置为当前时间
		if currentTask.StartTime == nil {
			updateData["start_time"] = &currentTime
			fmt.Printf("开始评价: 设置StartTime=%s (Unix: %d)\n",
				currentTime.Format("2006-01-02 15:04:05"),
				currentTime.Unix())
		} else {
			fmt.Printf("开始评价: StartTime已存在=%s (Unix: %d)，不更新\n",
				currentTask.StartTime.Format("2006-01-02 15:04:05"),
				currentTask.StartTime.Unix())
		}
		// LastStartTime每次都更新
		updateData["last_start_time"] = &currentTime
		fmt.Printf("开始评价: 更新LastStartTime=%s (Unix: %d)\n",
			currentTime.Format("2006-01-02 15:04:05"),
			currentTime.Unix())

	case 2: // 暂停评价
		// 根据传入的Time和LastStartTime的差值累加到RealDuration中
		if currentTask.LastStartTime != nil {
			fmt.Printf("=== 时间计算详情 ===\n")
			fmt.Printf("当前时间: %s (Unix: %d)\n", currentTime.Format("2006-01-02 15:04:05"), currentTime.Unix())
			fmt.Printf("开始时间: %s (Unix: %d)\n", currentTask.LastStartTime.Format("2006-01-02 15:04:05"), currentTask.LastStartTime.Unix())

			// 计算时间差（秒）
			durationSeconds := currentTime.Sub(*currentTask.LastStartTime).Seconds()
			duration := int(durationSeconds)

			fmt.Printf("Unix时间差: %d - %d = %d\n", currentTime.Unix(), currentTask.LastStartTime.Unix(), currentTime.Unix()-currentTask.LastStartTime.Unix())
			fmt.Printf("计算的持续时间: %.2f秒 -> %d秒\n", durationSeconds, duration)

			// 确保时间差为正数（避免时间倒退的情况）
			if duration > 0 {
				newRealDuration := currentTask.RealDuration + duration
				updateData["real_duration"] = newRealDuration
				fmt.Printf("暂停评价: 本次持续时间=%d秒, 累计时长=%d秒\n", duration, newRealDuration)
			} else {
				fmt.Printf("警告: 暂停时间计算出现负值，跳过时长累加. 当前时间=%s, 上次开始时间=%s\n",
					currentTime.Format("2006-01-02 15:04:05"),
					currentTask.LastStartTime.Format("2006-01-02 15:04:05"))
			}
		} else {
			fmt.Println("警告: LastStartTime为空，无法计算暂停时的时长")
		}

	case 3: // 终止评价
		// 记录EndTime
		updateData["end_time"] = &currentTime
		// 只有在之前的状态是1的情况下，才根据传入的Time和LastStartTime的差值累加到RealDuration中
		if currentTask.ExecStatus == 1 && currentTask.LastStartTime != nil {
			fmt.Printf("=== 时间计算详情 ===\n")
			fmt.Printf("当前时间: %s (Unix: %d)\n", currentTime.Format("2006-01-02 15:04:05"), currentTime.Unix())
			fmt.Printf("开始时间: %s (Unix: %d)\n", currentTask.LastStartTime.Format("2006-01-02 15:04:05"), currentTask.LastStartTime.Unix())

			// 计算时间差（秒）
			durationSeconds := currentTime.Sub(*currentTask.LastStartTime).Seconds()
			duration := int(durationSeconds)

			fmt.Printf("Unix时间差: %d - %d = %d\n", currentTime.Unix(), currentTask.LastStartTime.Unix(), currentTime.Unix()-currentTask.LastStartTime.Unix())
			fmt.Printf("计算的持续时间: %.2f秒 -> %d秒\n", durationSeconds, duration)

			// 确保时间差为正数（避免时间倒退的情况）
			if duration > 0 {
				newRealDuration := currentTask.RealDuration + duration
				updateData["real_duration"] = newRealDuration
				fmt.Printf("终止评价: 本次持续时间=%d秒, 最终累计时长=%d秒\n", duration, newRealDuration)
			} else {
				fmt.Printf("警告: 终止时间计算出现负值，跳过时长累加. 当前时间=%s, 上次开始时间=%s\n",
					currentTime.Format("2006-01-02 15:04:05"),
					currentTask.LastStartTime.Format("2006-01-02 15:04:05"))
			}
		} else if currentTask.ExecStatus != 1 {
			fmt.Printf("终止评价: 之前状态不是进行中(%d)，不累加时长\n", currentTask.ExecStatus)
		} else {
			fmt.Println("警告: LastStartTime为空，无法计算终止时的时长")
		}
	}

	// 执行更新操作
	result := db.Model(&dbModel.EvaluateTask{}).
		Where("id = ?", query.EvaluateTaskId).
		Updates(updateData)

	// 检查数据库操作错误
	if result.Error != nil {
		return fmt.Errorf("更新数据库失败: %v", result.Error)
	}

	if result.RowsAffected == 0 {
		return fmt.Errorf("更新失败，未找到ID为 %s 的评价任务", query.EvaluateTaskId)
	}

	fmt.Printf("===== 状态更新完成 =====\n")
	fmt.Printf("受影响行数: %d\n\n", result.RowsAffected)

	return nil
}

// 获取评价结果
func (manage *EvaluateTaskManage) GetEvaluateResult(query *request.GetEvaluateResultQuery) ([]response.GetEvaluateResultResponse, error) {
	db := manage.DataBase.DB()

	tx := db.Model(&dbModel.EvaluateResult{})
	tx = tx.Where("task_id = ?", query.EvaluateTaskId)
	
	// 如果有expertId，按原逻辑查询
	if query.ExpertId != "" {
		tx = tx.Where("expert_id=?", query.ExpertId)
		
		// 根据任务ID查询评价结果
		var evaluateResults []dbModel.EvaluateResult
		if err := tx.Order("quota_id ASC, expert_id ASC").Find(&evaluateResults).Error; err != nil {
			return nil, fmt.Errorf("查询评价结果失败: %v", err)
		}

		// 转换为响应格式
		var responseList []response.GetEvaluateResultResponse
		for _, result := range evaluateResults {
			responseItem := response.GetEvaluateResultResponse{
				Id:            result.Id,
				TemplateId:    result.TemplateId,
				QuotaId:       result.QuotaId,
				QuotaName:     result.QuotaName,
				ExpertId:      result.ExpertId,
				Score:         result.Score,
				AbsoluteScore: result.AbsoluteScore,
				SegmentScore:  result.SegmentScore,
				IsTotalScore:  result.IsTotalScore,
				Note:          result.Note,
			}
			responseList = append(responseList, responseItem)
		}
		return responseList, nil
	}

	// 如果没有expertId，查询所有结果并进行合并处理
	var evaluateResults []dbModel.EvaluateResult
	if err := tx.Order("quota_id ASC").Find(&evaluateResults).Error; err != nil {
		return nil, fmt.Errorf("查询评价结果失败: %v", err)
	}

	// 按quotaId分组合并，计算平均值
	quotaMap := make(map[string]*response.GetEvaluateResultResponse)
	quotaCountMap := make(map[string]int)

	for _, result := range evaluateResults {
		quotaId := result.QuotaId
		
		if existing, exists := quotaMap[quotaId]; exists {
			// 累加分数
			existing.Score += result.Score
			existing.AbsoluteScore += result.AbsoluteScore
			quotaCountMap[quotaId]++
		} else {
			// 第一次遇到该quotaId
			quotaMap[quotaId] = &response.GetEvaluateResultResponse{
				Id:            result.Id,
				TemplateId:    result.TemplateId,
				QuotaId:       result.QuotaId,
				QuotaName:     result.QuotaName,
				ExpertId:      "", // 不赋值
				Score:         result.Score,
				AbsoluteScore: result.AbsoluteScore,
				SegmentScore:  "", // 不赋值
				IsTotalScore:  result.IsTotalScore,
				Note:          "", // 不赋值
			}
			quotaCountMap[quotaId] = 1
		}
	}

	// 计算平均值并构建最终结果
	var responseList []response.GetEvaluateResultResponse
	for quotaId, item := range quotaMap {
		count := quotaCountMap[quotaId]
		if count > 1 {
			// 计算平均值
			item.Score = item.Score / float64(count)
			item.AbsoluteScore = item.AbsoluteScore / float64(count)
		}
		responseList = append(responseList, *item)
	}

	return responseList, nil
}

// 添加或修改评价结果
func (manage *EvaluateTaskManage) AddOrUpdateEvaluateResult(query *request.AddOrUpdateEvaluateResultQuery) error {
	if len(query.EvaluateResultList) == 0 {
		return nil
	}

	db := manage.DataBase.DB()
	// 获取模板信息
	var template dbModel.Template
	if err := db.Where("id = ?", query.TemplateId).First(&template).Error; err != nil {
		return fmt.Errorf("查询模板失败: %v", err)
	}

	// 获取当前模板所有指标
	var quotaList []dbModel.Quota
	quotaIdsMap := make(map[string]dbModel.Quota)
	if err := db.Where("template_id = ?", query.TemplateId).Find(&quotaList).Error; err != nil {
		return fmt.Errorf("查询指标失败: %v", err)
	}
	for _, quota := range quotaList {
		quotaIdsMap[quota.Id] = quota
	}

	// 开启事务确保数据一致性
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 先删除该用户对当前任务的所有评价结果
	if err := tx.Where("task_id = ? AND expert_id = ?", query.EvaluateTaskId, query.ExpertId).Delete(&dbModel.EvaluateResult{}).Error; err != nil {
		tx.Rollback()
		return fmt.Errorf("删除原有评价结果失败: %v", err)
	}

	// 批量创建新的评价结果
	var evaluateResults []dbModel.EvaluateResult
	for _, result := range query.EvaluateResultList {
		var absoluteScore float64 = 0
		quota, ok := quotaIdsMap[result.QuotaId]
		if !ok {
			absoluteScore = 0
		} else {
			if quota.EvaluationScore != nil {
				absoluteScore = float64(*quota.EvaluationScore) * result.Score / 10
			}
		}
		evaluateResult := dbModel.EvaluateResult{
			Id:            commUtils.GenUUID(),
			TaskId:        query.EvaluateTaskId,
			TemplateId:    query.TemplateId,
			QuotaId:       result.QuotaId,
			QuotaName:     result.QuotaName,
			ExpertId:      query.ExpertId,
			Score:         result.Score,
			AbsoluteScore: absoluteScore,
			SegmentScore:  result.SegmentScore,
			IsTotalScore:  result.IsTotalScore,
		}
		evaluateResults = append(evaluateResults, evaluateResult)
	}

	// 批量插入评价结果
	if len(evaluateResults) > 0 {
		if err := tx.CreateInBatches(evaluateResults, 100).Error; err != nil {
			tx.Rollback()
			return fmt.Errorf("创建评价结果失败: %v", err)
		}
	}

	// 计算总体评价结果
	var totalScore float64 = 0
	var totalAbsoluteScore float64 = 0
	for _, result := range evaluateResults {
		totalScore += result.Score
		totalAbsoluteScore += result.AbsoluteScore
	}

	// 添加总体评价结果
	if len(evaluateResults) > 0 {
		totalEvaluateResult := dbModel.EvaluateResult{
			Id:            commUtils.GenUUID(),
			TaskId:        query.EvaluateTaskId,
			TemplateId:    query.TemplateId,
			QuotaId:       "", // 总体评价结果不关联具体指标
			QuotaName:     "总体评价",
			ExpertId:      query.ExpertId,
			Score:         totalScore,
			AbsoluteScore: totalAbsoluteScore,
			SegmentScore:  "",
			IsTotalScore:  true, // 标识为总体评价结果
			Note:          query.Note,
		}

		// 插入总体评价结果
		if err := tx.Create(&totalEvaluateResult).Error; err != nil {
			tx.Rollback()
			return fmt.Errorf("创建总体评价结果失败: %v", err)
		}
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return fmt.Errorf("提交事务失败: %v", err)
	}

	return nil
}
